<template>
  <div class='pubedit'>
    <div class="edit-wrap" id="editor">
      <Toolbar style='border-bottom: 1px solid #ccc' :editor='editorRef' :defaultConfig='toolbarConfig' :mode='mode' />
      <Editor   style="height: 460px" v-model='editContentModel' 
  
      :defaultConfig='editorConfig' @onCreated='handleCreated'
        @onChange='handleChange' @customPaste="handPaste" :mode='mode' />
    </div>

  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

// import {getFilePath, getFileName} from '@/utils/common';
import { ElMessage, ElLoading } from 'element-plus';
import { previewUrl } from '@/api/minIOupload';
import { UploadPicMin } from '@/utils/minioUpload';
// import {createOss} from '@/utils/alioss.js';
import uploadStore from '@/store/modules/upload'
import { watch } from 'vue';
defineOptions({
  name: 'PubEditor'
})


const store = uploadStore();
const tem_url = ref('')
const props = defineProps({
  editContent: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '请输入内容...',
  },
  wangEditReadOnly:{
    type:Boolean,
    default:false
  }
});
const emits = defineEmits(['editContentEnv','imgUrlEnv','videoUrlEnv']);


const editContentModel = ref(props.editContent);
const editorRef = shallowRef();
const mode = ref('default');
const loading = ref(false);


watch(() => props.editContent, (nv) => {
  editContentModel.value = nv;
});

const toolbarConfig = {
  excludeKeys: [
    'insertVideo',
    'insertImage',
  ],
};

const editorConfig = {
  placeholder: props.placeholder,
  MENU_CONF: {},
  readOnly:props.wangEditReadOnly
};


function getBlob(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = function (event) {
      const arrayBuffer = event.target.result;
      const blob = new Blob([arrayBuffer], { type: file.type });
      resolve(blob);
    };
    reader.onerror = function (error) {
      reject(error);
    };
    reader.readAsArrayBuffer(file);
  });
}

//自定义富文本编辑器上传图片
editorConfig.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    if (file.size > (2 * 1024 * 1024)) return ElMessage.warning('图片过大，请在附件中上传')
    // insertFn(loadingGif);
    let blob = await getBlob(file)
    const updating = ElLoading.service({
      lock: true,
      text: '上传中请稍后...',
      background: 'rgba(0, 0, 0, 0.7)',
    });
    let file_id = await UploadPicMin(file, blob);
    let file_ids = []
    file_ids.push(file_id)
    // 通过files_id换取临时路径
    previewUrl({
      "file_ids": file_ids
    }).then(res => {
      tem_url.value = res[0][1]
      // 回显图像
       insertFn(tem_url.value);
        let imgUrl = `[file_id: ${file_id},url: ${tem_url.value}]`     
      // 将fi格式插入到内容后方
       emits("imgUrlEnv",imgUrl)

    })
    updating.close();
  },
};


//自定义上传视频
editorConfig.MENU_CONF['uploadVideo'] = {
  async customUpload(file, insertFn) {

    console.log(file);
    
    if (file.size > (100 * 1024 * 1024)) return ElMessage.warning('视频过大，请在附件中上传')

    const updating = ElLoading.service({
      lock: true,
      text: '上传中请稍后...',
      background: 'rgba(0, 0, 0, 0.7)',
    });

    if (!(file.type.match(/mp4/i) || file.type.match(/webm/i) || file.type.match(/ogg/i))) {
      ElMessage.error('视频只支持 mp4、ogg、webm 格式请自行转化后再上传！');
      return;
    }
    let res = await UploadPicMin(file);
    console.log(res);
    let file_id=res.file_id
    
    let file_ids = []
    file_ids.push(file_id)
    // 通过files_id换取临时路径
    previewUrl({
      "file_ids": file_ids
    }).then(res => {
      tem_url.value = res[0][1]
      // 回显视频
       insertFn(tem_url.value);
        let videoUrl = `[file_id: ${file_id},url: ${tem_url.value}]`     
      // 将fi格式插入到内容后方
       emits("videoUrlEnv",videoUrl)
    })
    // insertFn(res.url);
    updating.close();
  },
};


watch(() => store.videoProgress, nv => {
  if (loading.value) loading.value.text = '上传进度' + nv + '%';
});


// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // console.log( editor.getMenuConfig('insertVideo') )
  // console.log(editor.getAllMenuKeys())
  // console.log(editor.getConfig())
};

const handleChange = (editor) => {
  emits('editContentEnv', editor.getHtml());

};
//自定义粘贴
const handPaste = function (editor, event, callback) {
  const text = event.clipboardData.getData('text/plain');
  editor.insertText(text)
  event.preventDefault()
  callback(false)
}

</script>

<style lang='scss' scoped>
.pubedit {
  width: 100%;

  .edit-wrap {
    border: 1px solid #ccc;
  }
}
</style>
